Component({
  properties: {
    devicePosition: {
      type: String,
      value: 'back'
    },
    flashMode: {
      type: String,
      value: 'off'
    }
  },
  
  data: {
    cameraContext: null,
    cameraReady: false
  },
  
  lifetimes: {
    attached: function() {
      this.initCamera();
    },
    detached: function() {
      // 组件销毁时释放资源
      if (this.data.cameraContext) {
        this.data.cameraContext = null;
      }
    }
  },
  
  methods: {
    // 初始化相机
    initCamera: function() {
      const cameraContext = wx.createCameraContext(this);
      this.setData({
        cameraContext: cameraContext
      });
    },
    
    // 相机准备就绪
    onCameraReady: function() {
      this.setData({
        cameraReady: true
      });
      this.triggerEvent('ready');
    },
    
    // 相机错误处理
    onCameraError: function(e) {
      this.triggerEvent('error', e.detail);
    },
    
    // 拍照
    takePhoto: function() {
      if (!this.data.cameraReady) {
        this.triggerEvent('error', { errMsg: '相机未准备就绪' });
        return;
      }
      
      const cameraContext = this.data.cameraContext;
      cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          this.triggerEvent('photo', { tempImagePath: res.tempImagePath });
        },
        fail: (err) => {
          this.triggerEvent('error', err);
        }
      });
    }
  }
})